import 'dart:convert';
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:image_picker/image_picker.dart';
import 'package:http/http.dart' as http;
import 'package:proj_sfv/component/LoadingOverlay.dart';
import 'package:proj_sfv/domain/VideoDTO.dart';
import 'package:image_picker/image_picker.dart';
import 'package:proj_sfv/http/api.dart';
import 'package:proj_sfv/http/requests.dart';
import 'package:proj_sfv/pages/VideoEditPage.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:tencentcloud_cos_sdk_plugin/cos.dart';
import 'package:tencentcloud_cos_sdk_plugin/cos_transfer_manger.dart';
import 'package:tencentcloud_cos_sdk_plugin/fetch_credentials.dart';
import 'package:tencentcloud_cos_sdk_plugin/pigeon.dart';
import 'package:tencentcloud_cos_sdk_plugin/transfer_task.dart';
import 'package:video_player/video_player.dart';

import 'package:video_thumbnail/video_thumbnail.dart';

class CameraPage extends StatefulWidget {
  @override
  _CameraPage createState() => _CameraPage();
  const CameraPage();
}

class _CameraPage extends State<CameraPage> {
  File _videoFile;
  final picker = ImagePicker();
  final TextEditingController _nameController = TextEditingController();
  final TextEditingController _descriptionController = TextEditingController();
  final TextEditingController _tagsController = TextEditingController();
  int _id;
  String _token;
  bool _isLoading = false;
  double _progress = 0;
  bool _isPlaying = false;

  VideoPlayerController _controller;
  Future<void> _initializeVideoPlayerFuture;


  @override
  initState() {
    SharedPreferences.getInstance().then((value) {
      _id = value.getInt("id");
      _token = value.getString("token");
      if (_id == null) {
        Fluttertoast.showToast(msg: "请先登录");
      }
    });
  }


  Future<void> _pickVideo(ImageSource source) async {
    final pickedFile = await picker.pickVideo(source: source);
    setState(() {
      if (pickedFile != null) {
        _videoFile = File(pickedFile.path);
      }
      _controller = VideoPlayerController.file(_videoFile);
      _initializeVideoPlayerFuture =  _controller.initialize();
      _initializeVideoPlayerFuture.whenComplete(() {
        _controller.play();
        setState(() {
          _isPlaying = true;
        });
      });
    });
  }

  Future<void> _uploadVideo() async {
    if (_videoFile == null) {
      return;
    }
    setState(() {
      _isLoading = true;
    });
    final imageBytes = await VideoThumbnail.thumbnailData(
      video: _videoFile.path,
      imageFormat: ImageFormat.JPEG,
      maxHeight: 480,
      maxWidth: 480,
      timeMs: 5000,
      quality: 75,
    );
    String imageBase64 = base64Encode(imageBytes);
    var video = VideoDTO(_nameController.text, _id, DateTime.now(), true, false,
        _tagsController.text, _descriptionController.text, imageBase64);
    var sig = await uploadVideoForSigRequest(context, _token, video);
    print('sig: $sig');
    if (sig != null) {
        await Cos().initWithSessionCredential(FetchCredentials(sig));
        String region = "ap-nanjing";
        CosXmlServiceConfig serviceConfig = CosXmlServiceConfig(
          region: region,
          isDebuggable: true,
          isHttps: true,
        );
        TransferConfig transferConfig = TransferConfig(
          forceSimpleUpload: false,
          enableVerification: true,
          divisionForUpload: 2097152, // 设置大于等于 2M 的文件进行分块上传
          sliceSizeForUpload: 1048576, //设置默认分块大小为 1M
        );
        await Cos().registerDefaultTransferManger(serviceConfig, transferConfig);
        CosTransferManger transferManager = Cos().getDefaultTransferManger();
        String bucket = "video-1308753508";
        String cosPath = sig['id']; //对象在存储桶中的位置标识符，即称对象键
        String srcPath = _videoFile.path; //本地文件的绝对路径
        //若存在初始化分块上传的 UploadId，则赋值对应的 uploadId 值用于续传；否则，赋值 null
        String _uploadId;

        // 上传成功回调
        successCallBack(result) {
          Fluttertoast.showToast(msg: "上传成功");
          setState(() {
            _isLoading = false;
            _tagsController.clear();
            _descriptionController.clear();
            _nameController.clear();
            _videoFile = null;
            _controller.pause();
          });
        }
        //上传失败回调
        failCallBack(clientException, serviceException) {
          // todo 上传失败后的逻辑
          if (clientException != null) {
            var exception = clientException as CosXmlClientException;
            print("客户端异常为：${exception.details} ${exception.errorCode} "
                "${exception.message} ${exception.errorCode}");
          }
          if (serviceException != null) {
            print("服务端异常为 $serviceException");
          }
          setState(() {
            _isLoading = false;
          });
        }
        //上传状态回调, 可以查看任务过程
        stateCallback(state) {
        }
        //上传进度回调
        progressCallBack(complete, target) {
          setState(() {
            _progress = complete / target;
          });
        }
        //初始化分块完成回调
        initMultipleUploadCallback(
            String bucket, String cosKey, String uploadId) {
          //用于下次续传上传的 uploadId
          _uploadId = uploadId;
        }
        //开始上传
        TransferTask transferTask = await transferManager.upload(bucket, cosPath,
            filePath: srcPath,
            uploadId: _uploadId,
            resultListener: ResultListener(successCallBack, failCallBack),
            stateCallback: stateCallback,
            progressCallBack: progressCallBack,
            initMultipleUploadCallback: initMultipleUploadCallback,
        );
    }
    // 上传文件
    // request.files.add(await http.MultipartFile.fromPath('video', _videoFile.path));
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: LoadingOverlay(
        isLoading: _isLoading,
        isHidden: true,
        child: Column(
          children: [
            Expanded(
              child: Center(
                child: FutureBuilder(
                  future: _initializeVideoPlayerFuture,
                  builder: (context, snapshot) {
                    if (snapshot.connectionState == ConnectionState.done) {
                      return AspectRatio(
                        aspectRatio: _controller.value.aspectRatio,
                        child: InkWell(
                            splashColor: Colors.white24,
                            onTap: () async {
                              if (_videoFile == null)
                                return;
                              String newPath = await Navigator.push(context, MaterialPageRoute(builder: (build) => VideoEditPage(_videoFile.path,
                                  _controller.value.duration.inSeconds)));
                              setState(() {
                                _videoFile = File(newPath);
                                _controller = VideoPlayerController.file(_videoFile);
                              });
                              await _controller.initialize();
                              _controller.play();
                            } ,
                            child: VideoPlayer(_controller)
                        ),
                      );
                    } else {
                      return CircularProgressIndicator();
                    }
                  },
                ),
                // child: _videoFile == null
                //     ? Text('请拍摄一段视频')
                //     : Text('已选择视频：${_videoFile.path}'),
              ),
            ),
            TextField(
              controller: _nameController,
              decoration: InputDecoration(
                labelText: '名称',
              ),
            ),
            TextField(
              controller: _descriptionController,
              decoration: InputDecoration(
                labelText: '简介',
              ),
            ),
            TextField(
              controller: _tagsController,
              decoration: InputDecoration(
                labelText: '标签（多个标签用逗号隔开）',
              ),
            ),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              children: [
                ElevatedButton(
                  onPressed: () => _pickVideo(ImageSource.camera),
                  child: Text('打开相机'),
                ),
                ElevatedButton(
                  onPressed: () => _pickVideo(ImageSource.gallery),
                  child: Text('打开相册'),
                ),
                ElevatedButton(
                    onPressed: _videoFile == null ? null : () async {
                      _isPlaying ?  _controller.pause(): _controller.play();
                      setState(() {
                        _isPlaying = !_isPlaying;
                      });
                    },
                    child: _isPlaying ? Text("暂停") : Text("播放")
                ),
                ElevatedButton(
                  onPressed: _videoFile == null ? null : _uploadVideo,
                  child: Text('上传'),
                ),
                // ElevatedButton(onPressed: () {
                //   print('长度 ${_controller.value.duration.inSeconds}');
                //   }, child: Text("测试"),)
              ],
            ),
            // TODO 选择封面控件
          ],
        ),
      ),
      floatingActionButton: LoadingOverlay1(
        isLoading: _isLoading,
        progress: _progress,
      ),
    );
  }
}

class FetchCredentials implements IFetchCredentials {

  Map<String, dynamic> map;


  FetchCredentials(this.map);

  @override
  Future<SessionQCloudCredentials> fetchSessionCredentials() async {
    return SessionQCloudCredentials(
        secretId: map['tmpSecretId'],
        secretKey: map['tmpSecretKey'],
        token: map['token'],
        expiredTime: map['expireTime'],
        startTime: map['startTime']
    );
  }

}
